package com.frogs.ucenter.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.base.web.BaseController3;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.StringUtil;
import com.frogs.framework.web.HttpRequestInfo;
import com.frogs.framework.web.HttpResponseUtil;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.util.OrderStatusEnum;
import com.frogs.system.util.UserAccountInfoStatusEnum;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.ucenter.component.UserPermissionHelper;
import com.frogs.ucenter.entity.UserBaseAccountInfo;
import com.frogs.ucenter.entity.UserIntegralBalance;
import com.frogs.ucenter.entity.UserRechargeRecord;
import com.frogs.ucenter.service.PayCenterService;
import com.frogs.ucenter.service.UserIntegralService;
import com.frogs.ucenter.service.UserRechargeService;
import com.frogs.ucenter.service.UserRechargeableCardService;
import com.frogs.ucenter.util.Constants;
import com.frogs.ucenter.util.PaymentEnum;
import com.frogs.ucenter.util.SignVerifyUtil;

/**
 * 个人资产
 *
 * @author lijian
 * @version 2014年8月5日 - 上午10:10:22
 */
@Controller
public class UserPropertyController extends BaseController3 {

	private static Logger log = LoggerFactory.getLogger(UserPropertyController.class);
	
	private static final String HOME_VIEW = "property/index";
	private static final String RECHARGE_VIEW = "property/recharge";
	private static final String RECHARGE_RECORD_VIEW = "property/recharge_record";
	private static final String BALANCE_CONSUME_VIEW = "property/balance_consume";
	private static final String PAY_RESULT_VIEM = "property/pay_result";
	private static final String INTEGRAL_VIEW = "property/integral";
	private static final String INTEGRAL_REORD_VIEW = "property/integral_record";

	private static final String HOME = "/property/index";
	private static final String RECHARGE = "/property/recharge";
	private static final String INTEGRAL = "/property/integral";
	private static final String INTEGRAL_RECORD = "/property/integralRecord";
	private static final String RECHARGE_RECORD = "/property/rechargeRecord";
	private static final String BALANCE_CONSUME = "/property/balanceConsume";
	private static final String PAY = "/recharge/pay";
	private static final String PAYCALL_BACK = "/recharge/paycallback";
	private static final String RECHARGEABLE_CARD_CONSUME = "/rechargeableCard/consume";
	
	private static final String COOKIE_RECHARGE_RECORD_ID = "rrid";
    
    @Resource
    private UserRechargeableCardService userRechargeableCardService;
    @Resource
    private UserRechargeService userRechargeService;
    @Resource
    private UserIntegralService userIntegralService;
    @Resource
    private PayCenterService payCenterService;
	@Resource
	private UserPermissionHelper userPermissionHelper;
	@Resource
	protected Map<String, String> payApiConfig;
    
    @RequestMapping(HOME)
    public String home(HttpServletRequest request, ModelMap model) {
    	try {
    		UserBaseAccountInfo user = userPermissionHelper.getUser(request);
    		model.put("userNickname", user.getNickName());
    		
		} catch (Exception e) {
			log.error("func[home] parameterMap[{}] exception[{} - {}] desc[fail]",//
					new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			request.setAttribute("errorMessage", e.getMessage());
			return ERROR_VIEW;
		}
    	return HOME_VIEW;
    }
    
    /**
     * 充值页面
     * 
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(RECHARGE)
    public String recharge(HttpServletRequest request, ModelMap model) throws Exception {
		
		UserBaseAccountInfo user = userPermissionHelper.getUser(request);
		// 余额查询
		getUserbalance(user, model);
    	return RECHARGE_VIEW;
    }
    
    /**
     * 充值记录
     * 
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(RECHARGE_RECORD)
    public String rechargeRecordList(HttpServletRequest request, ModelMap model) {
    	try {
    		HttpRequestInfo reqInfo = new HttpRequestInfo(request);
    		Integer pageNo = reqInfo.getIntParameter("pageNo", 1);
    		Integer pageSize = reqInfo.getIntParameter("pageSize", 10);
    		UserBaseAccountInfo user = userPermissionHelper.getUser(request);
    		// 余额查询
    		getUserbalance(user, model);
    		
    		PageList<Map<String, Object>> list = userRechargeService.getUserRechargeRecordList(user.getId(), pageNo, pageSize, user.getVerify());
    		model.put("userRechargeRecordList", list);
    		model.put("pageTurn", list.getPageTurn());
    	} catch (Exception e) {
			log.error("func[rechargeRecordList] parameterMap[{}] exception[{} - {}] desc[fail]",//
					new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			request.setAttribute("errorMessage", e.getMessage());
			return ERROR_VIEW;
		}
    	return RECHARGE_RECORD_VIEW;
    }
    
    /**
     * 余额消费记录
     * 
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(BALANCE_CONSUME)
    public String balanceConsumeList(HttpServletRequest request, ModelMap model) {
    	try {
    		HttpRequestInfo reqInfo = new HttpRequestInfo(request);
    		
    		Integer pageNo = reqInfo.getIntParameter("pageNo", 1);
    		Integer pageSize = reqInfo.getIntParameter("pageSize", 10);
    		UserBaseAccountInfo user = userPermissionHelper.getUser(request);
    		// 余额查询
    		getUserbalance(user, model);
    		PageList<Map<String, Object>> list = userRechargeService.getUserConsumeRecordList(user.getId(), pageNo, pageSize, user.getVerify());
    		model.put("userBalanceConsumeList", list);
    		model.put("pageTurn", list.getPageTurn());
    		
    	} catch (Exception e) {
			log.error("func[balanceConsumeList] parameterMap[{}] exception[{} - {}] desc[fail]",//
					new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			request.setAttribute("errorMessage", e.getMessage());
			return ERROR_VIEW;
		}
    	return BALANCE_CONSUME_VIEW;
    }
    

    /**
     * 充值卡充值
     * 
     * @param request
     * @param model
     */
    @RequestMapping(RECHARGEABLE_CARD_CONSUME)
    public JSONObject rechargeableCardConsume(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
    	try {
	    	HttpRequestInfo requestInfo = new HttpRequestInfo(request);
	    	UserBaseAccountInfo user = userPermissionHelper.getUser(request);
    		String rechargeCard = requestInfo.getParameter(ApiUrlParamEnum.rechargeCard.getParamName());
    		String passwd = requestInfo.getParameter(ApiUrlParamEnum.password.getParamName());

	    	if (UserAccountInfoStatusEnum.AVAILABILITY_NO.getId() == user.getIsPhoneValid()) {
	    		
	    		String result = "{\"response\":{\"code\":"+ApiResultEnum.FAIL.getId()+",\"tip\":\"您的账号尚未绑定手机号码，请先绑定手机号码再充值\"}}";
	    		JSONObject errorObject = JSON.parseObject(result);
	    		return errorObject;
	    	}
	    	
	    	return userRechargeableCardService.consume(user.getId(), rechargeCard, passwd, PaymentEnum.card_0.getName());

    	} catch (Exception e) {
			log.error("func[rechargeableCardConsume] parameterMap[{}] exception[{} - {}] desc[fail]",//
					new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}
    	return null;
    }
    
    
    /**
     * 支付
     * 
     * @param request
     * @param model
     */
    @RequestMapping(PAY)
    public String pay(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
    	try {
	    	HttpRequestInfo requestInfo = new HttpRequestInfo(request);
	    	UserBaseAccountInfo user = userPermissionHelper.getUser(request);
	    	String bank = requestInfo.getParameter("bank", "");
	    	BigDecimal rechargeMoney = requestInfo.getBigDecimalParameter("rechargeMoney");
	    	log.info("func[pay] bank[" + bank + "] rechargeMoney[" + rechargeMoney + "] desc[params]");
	    	model.put("userNickname", user.getNickName());
	    	if (UserAccountInfoStatusEnum.AVAILABILITY_NO.getId() == user.getIsPhoneValid()) {
	    		model.put("errorMessage", "您的账号尚未绑定手机号码，请先绑定手机号码再充值");
	    		return ERROR_VIEW;
	    	}
	    	if(!userRechargeService.verifyUserBalance(user.getId(), user.getVerify())) {
	    		model.put("errorMessage", "您账号的余额出现异常，请联系客服");
	    		return ERROR_VIEW;
	    	}
    		if (StringUtil.isEmpty(bank)) {
    			model.put("errorMessage", "请选择支付方式");
	    		return ERROR_VIEW;
    		}
	    	if (rechargeMoney == null) {
	    		model.put("errorMessage", "请输入金额");
	    		return ERROR_VIEW;
	    	}
	    	String channelKey = "";
	    	String channelName = "";
	    	String ebankKey = "";
	    	String ebankName = "";
    		String[] sb = bank.split(",");
    		if (sb.length > 1) {
    			channelKey = sb[0];
        		ebankKey = sb[1];
        		ebankName = PaymentEnum.getByKey(channelKey+ebankKey).getName();
    		} else {
    			channelKey = sb[0];
    		}
    		channelName = PaymentEnum.getByKey(channelKey).getName();
	    	model.put("channelKey", channelKey);
	    	model.put("channelName", channelName);
	    	model.put("ebankKey", ebankKey);
	    	model.put("ebankName", ebankName);
	    	// 创建一条充值记录
	    	String rechargeFrom = channelName + (!"".equals(ebankName) ? "_" +ebankName : "");
	    	
	    	UserRechargeRecord userRechargeRecord = userRechargeService.addUserRechargeRecord(user.getId(), rechargeMoney, "", rechargeFrom, user.getVerify());
	    	HttpResponseUtil.setCookie(response, COOKIE_RECHARGE_RECORD_ID, userRechargeRecord.getId().toString(), "uc.frogshealth.com", "/");
	    	log.info("func[pay] user["+user+"] recordId[" + userRechargeRecord.getId() + "] userRechargeRecord["+ userRechargeRecord + "] desc[pay before]");
	    	// 跳到支付页面(是否需要一个中转页)
	    	response.sendRedirect(payApiConfig.get("PAY_URL") + "?" + _preparePayInitParams(user, userRechargeRecord, model));
	    	return null;
    	} catch (Exception e) {
			log.error("func[pay] parameterMap[{}] exception[{} - {}] desc[fail]",//
					new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			request.setAttribute("errorMessage", e.getMessage());
			return ERROR_VIEW;
		}
    }
    
    /**
     * 支付回调
     * 
     * @param request
     * @param model
     */
    @RequestMapping(PAYCALL_BACK)
    public String payCallBack(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
    	try {
	    	// 查询充值记录的支付状态
	    	HttpRequestInfo requestInfo = new HttpRequestInfo(request);
	    	String orderSn = requestInfo.getParameter("orderSn", "");
	    	if (StringUtil.isEmpty(orderSn)) {
	    		orderSn = requestInfo.getCookieValue(COOKIE_RECHARGE_RECORD_ID, "");
	    		if (StringUtil.isEmpty(orderSn)) {
	    			log.error("func[payCallBack] desc[orderSn is null]");
		    		model.put("message", "参数丢失");
		    		model.put("code", 0);
					return PAY_RESULT_VIEM;
	    		}
	    	}
	    	UserBaseAccountInfo user = userPermissionHelper.getUser(request);
	    	UserRechargeRecord userRechargeRecord = userRechargeService.getUserRechargeRecordInfo(user.getId(), Integer.valueOf(orderSn), user.getVerify());
	    	if (userRechargeRecord != null && userRechargeRecord.getStatus() == OrderStatusEnum.ORDER_STATUS_YES.getId()) {
	    		model.put("message", "支付成功");
	    		model.put("code", 1);
		    	HttpResponseUtil.setCookie(response, COOKIE_RECHARGE_RECORD_ID, null, ".frogshealth.com", "/");
	    		return PAY_RESULT_VIEM;
	    	} else {
	    		log.error("func[payCallBack] userRechargeRecord[" + userRechargeRecord + "] desc[orderSn is null]");
	    		model.put("message", "支付失败");
	    		model.put("code", 0);
				return PAY_RESULT_VIEM;
	    	}
    	} catch (Exception e) {
			log.error("func[payCallBack] parameterMap[{}] exception[{} - {}] desc[fail]",//
					new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			request.setAttribute("errorMessage", e.getMessage());
			return ERROR_VIEW;
		}
    }
    
    /**
     * 支付需要参数
     * 
     * @param request
     * @param model
     * @return
     */
    protected String _preparePayInitParams(UserBaseAccountInfo user, UserRechargeRecord userRechargeRecord, ModelMap model) {
    	 Map<String, String> params = new HashMap<String, String>();
    	 
    	 //支付需要参数
    	 params.put("uuid", payApiConfig.get("UUID"));
    	 params.put("token", payApiConfig.get("ACCESS_TOKEN"));
    	 params.put("orderSn", userRechargeRecord.getId().toString()); // 充值ID
    	 params.put("orderSource", "ucenter");
    	 params.put("amount", userRechargeRecord.getRechargeMoney().toString()); // 金钱
    	 params.put("notifyUrl", payApiConfig.get("NOTIFY_URL")); // 支付异步回调地址
    	 params.put("returnUrl", payApiConfig.get("RETURN_URL")); // 支付成功返回的页面地址
    	 params.put("orderDesc", "余额充值"); // 描述
    	 params.put("productName", "余额充值");
    	 params.put("channelKey", model.get("channelKey").toString()); // 第三方支付的渠道key
    	 params.put("channelName", model.get("channelName").toString()); // 第三方支付的名称
    	 params.put("ebankKey", model.get("ebankKey").toString()); // 银行key,快钱支付时，此字段必传
    	 params.put("ebankName", model.get("ebankName").toString()); // 银行名称
    	 params.put("buyerUserId", user.getId().toString()); // 用户ID
    	 params.put("buyerUserName", user.getAccountName()); // 用户名
    	 params.put("payType", "2"); //1：订单支付 2：余额充值
    	 String sign = SignVerifyUtil.sign(params, Constants.PAY_SIGN_KEY);
    	 
 		 params.put("sign", sign.toLowerCase());
 		 String queryString = SignVerifyUtil.createLinkString(params, true);
 		 log.info("func[_preparePayInitParams] queryString[" + queryString+ "] desc[params]");
 		 return queryString;
    }
    
    /**
     * 余额查询
     * 
     * @param request
     * @param model
     * @throws Exception
     */
    private void getUserbalance(UserBaseAccountInfo user, ModelMap model) throws Exception {
		model.put("userBalance", userRechargeService.getUserBalanceInfo(user.getId(), user.getVerify()));
    }
    
    /**
     * 积分查询
     */
    @RequestMapping(INTEGRAL)
    public String integral(HttpServletRequest request, ModelMap model) throws Exception {
    	HttpRequestInfo reqInfo = new HttpRequestInfo(request);
		
		Integer pageNo = reqInfo.getIntParameter("pageNo", 1);
		Integer pageSize = reqInfo.getIntParameter("pageSize", 10);
		UserBaseAccountInfo user = userPermissionHelper.getUser(request);
		PageList<Map<String, Object>> list = userIntegralService.getUserIntegralConsumeRecordList(user.getId(), pageNo, pageSize);
		model.put("integralConsumeRecordList", list);
		model.put("pageTurn", list.getPageTurn());
		
		UserIntegralBalance integralBalance = userIntegralService.getUserIntegralInfo(user.getId());
		if(null != integralBalance) {
			model.put("integralBalance", integralBalance.getIntegralUsable());
		} else {
			model.put("integralBalance", 0);
		}
		
    	return INTEGRAL_VIEW;
    }  

    /**
     * 积分记录
     */
    @RequestMapping(INTEGRAL_RECORD)
    public String integralRecord(HttpServletRequest request, ModelMap model) throws Exception {
    	HttpRequestInfo reqInfo = new HttpRequestInfo(request);
		Integer pageNo = reqInfo.getIntParameter("pageNo", 1);
		Integer pageSize = reqInfo.getIntParameter("pageSize", 10);
		UserBaseAccountInfo user = userPermissionHelper.getUser(request);
		PageList<Map<String, Object>> list = userIntegralService.getUserIntegralRecordList(user.getId(), pageNo, pageSize);
		model.put("integralRecordList", list);
		model.put("pageTurn", list.getPageTurn());
		
		UserIntegralBalance integralBalance = userIntegralService.getUserIntegralInfo(user.getId());
		if(null != integralBalance) {
			model.put("integralBalance", integralBalance.getIntegralUsable());
		} else {
			model.put("integralBalance", 0);
		}
	
    	return INTEGRAL_REORD_VIEW;
    }
}
